from django.contrib.auth.decorators import login_required
#from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
#from django.views.generic.create_update import update_object

from django.contrib.auth.models import Group as Project
from .models import Document, Requirement

@login_required
def index(r):
   return render_to_response('rat/index.html', {'user': r.user})

## @login_required
## def modify_document(r, document_id):
##    return update_object(r, model=Document, object_id=document_id)
   
## @login_required
## def add_requirement_to_document(r, document_id):
##    document = get_object_or_404(Document, pk=document_id)
##    newrequirement = Requirement(document=document, order=-1)
##    newrequirement.save ()
##    newrequirement.order = newrequirement.id
##    newrequirement.save ()
##    return HttpResponseRedirect('/rat/document/%s'% document_id)

@login_required
def documents_in_project(request, project_id):
   error = None
   project = get_object_or_404(Project, pk=project_id)
   POST = request.POST
   if 'new_document' in POST and POST['new_document']:
      name = POST['new_document']
      d = Document(project=project, name=name, prefix=name)
      try:
         d.save()
      except Exception, msg:
         error = msg
   return render_to_response(
      'rat/documents_in_project.html', {
      'error': error,
      'user': request.user,
      "project": project})

@login_required
def requirements_in_document(request, project_id, document_id):
   error = None
   project = get_object_or_404(Project, pk=project_id)
   document = get_object_or_404(Document, pk=document_id)
   return render_to_response('rat/requirements_in_document.html', {
      'error': error,
      'user': request.user,
      'project': project,
      'document': document})

## @login_required
## def dynamic_requirements_in_document(r, document_id):
##    document = get_object_or_404(Document, pk=document_id)
##    return render_to_response('rat/dynamic_requirements.html', {
##       "document": document,
##       "requirement_list": Requirement.objects.filter(document=document_id)})

@login_required
def requirement(request, project_id, document_id, requirement_id):
   error = None
   project = get_object_or_404(Project, pk=project_id)
   document = get_object_or_404(Document, pk=document_id)
   requirement = get_object_or_404(Requirement, pk=requirement_id)
   return render_to_response('rat/requirement.html', {
      'error': error,
      'user': request.user,
      "requirement": requirement})
